import cron from 'node-cron';
import { getBufferedEntries, clearBuffer } from './SensorSnapshotBuffer';
import { processSensorSnapshot } from './processSensorSnapshot';

console.log('[SCHEDULER] 传感器定时采样器模块已加载');


cron.schedule('0 * * * *', async () => {
   const now = new Date();

   //  targetHourStart 是当前小时的开始
  const targetHourStart = new Date(now);
  targetHourStart.setMinutes(0, 0, 0);
  targetHourStart.setSeconds(0, 0);
  targetHourStart.setMilliseconds(0);

  console.log(`[CRON] ${now.toISOString()} - 整点采样任务触发`);

  const entries = getBufferedEntries();
  if (entries.length === 0) {
    console.log('[CRON] 当前无缓存传感器数据');
  }

  for (const { did, data, userId } of entries) {
    await processSensorSnapshot(did, data, userId, targetHourStart);
  }

  clearBuffer(); // 处理完再清空
  console.log(`[CRON] 采样完成：处理 ${entries.length} 条数据, 缓存已清空`);
});
